# import matplotlib.pyplot as plt
# import matplotlib.patches as patches
# from matplotlib.patches import FancyBboxPatch, Rectangle, ConnectionPatch
# import numpy as np
# from io import BytesIO
# import base64
#
#
# class IntelligentWorkoverSystemArchitecture:
#     """智能修井系统三层协同架构"""
#
#     def __init__(self):
#         self.fig = None
#         self.ax = None
#         self.setup_architecture()
#
#     def setup_architecture(self):
#         """设置架构组件和数据流"""
#         self.layers = {
#             "cloud": {
#                 "name": "☁️ 云端层 - 智慧大脑\n(全局监控、规划与优化)",
#                 "color": "#E3F2FD",
#                 "components": {
#                     "远程监控中心 HMI": {"pos": (0.5, 0.85), "color": "#FFEB3B"},
#                     "数字孪生体": {"pos": (0.25, 0.75), "color": "#4CAF50"},
#                     "修井预演模块": {"pos": (0.25, 0.65), "color": "#2196F3"},
#                     "大数据分析与AI平台": {"pos": (0.75, 0.75), "color": "#9C27B0"},
#                     "远程专家诊断系统": {"pos": (0.75, 0.65), "color": "#F44336"}
#                 }
#             },
#             "edge": {
#                 "name": "边缘层 - 智能中枢\n(本地实时决策与控制)",
#                 "color": "#F3E5F5",
#                 "components": {
#                     "边缘服务器集群": {"pos": (0.5, 0.45), "color": "#FF9800"},
#                     "协同运动规划器": {"pos": (0.15, 0.4), "color": "#3F51B5"},
#                     "机器视觉处理引擎": {"pos": (0.3, 0.4), "color": "#00BCD4"},
#                     "实时控制逻辑": {"pos": (0.7, 0.4), "color": "#8BC34A"},
#                     "数据网关(OPC UA/MQTT)": {"pos": (0.85, 0.4), "color": "#607D8B"},
#                     "本地操作台接口": {"pos": (0.5, 0.35), "color": "#E91E63"}
#                 }
#             },
#             "field": {
#                 "name": "现场层 - 执行手足\n(信号采集与驱动)",
#                 "color": "#E8F5E8",
#                 "components": {
#                     "PLC控制系统": {"pos": (0.2, 0.2), "color": "#3F51B5"},
#                     "机器人控制器": {"pos": (0.4, 0.2), "color": "#3F51B5"},
#                     "伺服驱动器系统": {"pos": (0.6, 0.2), "color": "#FF5722"},
#                     "传感器网络": {"pos": (0.8, 0.15), "color": "#673AB7"},
#                     "执行器系统": {"pos": (0.8, 0.1), "color": "#E53935"},
#                     "基地预装系统": {"pos": (0.2, 0.1), "color": "#795548"},
#                     "弹夹式管盒": {"pos": (0.1, 0.08), "color": "#A1887F"},
#                     "工具集装架": {"pos": (0.3, 0.08), "color": "#A1887F"}
#                 }
#             }
#         }
#
#         # 定义数据流
#         self.data_flows = [
#             # 云端内部流
#             ("数字孪生体", "修井预演模块", "预演生成", "blue"),
#             ("修井预演模块", "远程监控中心 HMI", "任务包提交", "blue"),
#
#             # 云端 -> 边缘
#             ("远程监控中心 HMI", "边缘服务器集群", "指令下发", "green"),
#             ("大数据分析与AI平台", "边缘服务器集群", "优化策略", "green"),
#             ("远程专家诊断系统", "边缘服务器集群", "诊断指令", "green"),
#
#             # 云端 -> 现场 (调度)
#             ("远程监控中心 HMI", "基地预装系统", "调度指令", "purple"),
#
#             # 边缘内部流
#             ("本地操作台接口", "边缘服务器集群", "模式切换", "orange"),
#
#             # 边缘 -> 现场 (控制)
#             ("边缘服务器集群", "PLC控制系统", "协同控制指令", "red"),
#             ("协同运动规划器", "机器人控制器", "运动轨迹", "red"),
#             ("机器视觉处理引擎", "机器人控制器", "视觉引导", "red"),
#             ("实时控制逻辑", "伺服驱动器系统", "驱动指令", "red"),
#
#             # 现场 -> 边缘 (反馈)
#             ("传感器网络", "数据网关(OPC UA/MQTT)", "实时数据", "brown"),
#             ("执行器系统", "数据网关(OPC UA/MQTT)", "状态反馈", "brown"),
#             ("PLC控制系统", "边缘服务器集群", "设备状态", "brown"),
#
#             # 边缘 -> 云端 (数据上传)
#             ("边缘服务器集群", "远程监控中心 HMI", "聚合数据", "navy"),
#             ("边缘服务器集群", "数字孪生体", "实时同步", "navy"),
#             ("边缘服务器集群", "大数据分析与AI平台", "分析数据", "navy"),
#             ("边缘服务器集群", "远程专家诊断系统", "诊断数据", "navy")
#         ]
#
#     def create_architecture_diagram(self, save_path=None):
#         """创建架构图"""
#         plt.close('all')  # 关闭之前的图
#
#         self.fig, self.ax = plt.subplots(1, 1, figsize=(20, 15))
#         self.ax.set_xlim(0, 1)
#         self.ax.set_ylim(0, 1)
#         self.ax.set_aspect('equal')
#         self.ax.axis('off')
#
#         # 设置背景
#         self.ax.set_facecolor('#f8f9fa')
#
#         # 绘制标题
#         self.ax.text(0.5, 0.96, '智能修井机器人系统\n三层协同架构',
#                      ha='center', va='center', fontsize=20, fontweight='bold',
#                      bbox=dict(boxstyle="round,pad=0.5", facecolor='white', edgecolor='black'))
#
#         # 绘制各层
#         self._draw_layers()
#
#         # 绘制组件
#         self._draw_components()
#
#         # 绘制数据流
#         self._draw_data_flows()
#
#         # 添加图例
#         self._add_legend()
#
#         plt.tight_layout()
#
#         if save_path:
#             plt.savefig(save_path, dpi=300, bbox_inches='tight')
#             print(f"架构图已保存至: {save_path}")
#
#         return self.fig
#
#     def _draw_layers(self):
#         """绘制三层区域"""
#         layer_heights = {'cloud': 0.25, 'edge': 0.2, 'field': 0.2}
#         layer_y_positions = {'cloud': 0.7, 'edge': 0.45, 'field': 0.2}
#
#         for layer_id, layer_info in self.layers.items():
#             y_pos = layer_y_positions[layer_id]
#             height = layer_heights[layer_id]
#
#             # 绘制层背景
#             rect = FancyBboxPatch((0.02, y_pos - height / 2), 0.96, height,
#                                   boxstyle="round,pad=0.02", linewidth=2,
#                                   facecolor=layer_info['color'], edgecolor='black', alpha=0.8)
#             self.ax.add_patch(rect)
#
#             # 层标题
#             self.ax.text(0.5, y_pos + height / 2 - 0.05, layer_info['name'],
#                          ha='center', va='center', fontsize=14, fontweight='bold',
#                          bbox=dict(boxstyle="round,pad=0.3", facecolor='white', alpha=0.9))
#
#     def _draw_components(self):
#         """绘制所有组件"""
#         for layer_id, layer_info in self.layers.items():
#             for comp_name, comp_info in layer_info['components'].items():
#                 x, y = comp_info['pos']
#
#                 # 绘制组件框
#                 width, height = 0.16, 0.04
#                 if len(comp_name) > 8:  # 长名称调整宽度
#                     width = 0.2
#
#                 rect = FancyBboxPatch((x - width / 2, y - height / 2), width, height,
#                                       boxstyle="round,pad=0.01", linewidth=1.5,
#                                       facecolor=comp_info['color'], edgecolor='black', alpha=0.9)
#                 self.ax.add_patch(rect)
#
#                 # 组件名称
#                 fontsize = 8 if len(comp_name) <= 12 else 7
#                 self.ax.text(x, y, comp_name, ha='center', va='center',
#                              fontsize=fontsize, fontweight='bold',
#                              bbox=dict(boxstyle="round,pad=0.1", facecolor='white', alpha=0.8))
#
#     def _draw_data_flows(self):
#         """绘制数据流箭头"""
#         arrow_style = "->,head_width=0.05,head_length=0.1"
#
#         for source, target, label, color in self.data_flows:
#             source_pos = self._find_component_position(source)
#             target_pos = self._find_component_position(target)
#
#             if source_pos and target_pos:
#                 # 计算箭头路径
#                 dx = target_pos[0] - source_pos[0]
#                 dy = target_pos[1] - source_pos[1]
#
#                 # 绘制箭头
#                 self.ax.annotate("", xy=target_pos, xytext=source_pos,
#                                  arrowprops=dict(arrowstyle=arrow_style,
#                                                  color=color, alpha=0.7, lw=2))
#
#                 # 数据流标签
#                 mid_x = (source_pos[0] + target_pos[0]) / 2
#                 mid_y = (source_pos[1] + target_pos[1]) / 2
#
#                 # 根据方向调整标签位置避免重叠
#                 label_offset = 0.02
#                 if abs(dy) > abs(dx):  # 垂直流向
#                     label_x = mid_x + label_offset
#                 else:  # 水平流向
#                     label_y = mid_y + label_offset
#
#                 self.ax.text(mid_x, mid_y, label, fontsize=7, ha='center', va='center',
#                              bbox=dict(boxstyle="round,pad=0.2", facecolor='white',
#                                        edgecolor=color, alpha=0.8))
#
#     def _find_component_position(self, component_name):
#         """查找组件位置"""
#         for layer_info in self.layers.values():
#             for comp_name, comp_info in layer_info['components'].items():
#                 if comp_name == component_name:
#                     return comp_info['pos']
#         return None
#
#     def _add_legend(self):
#         """添加图例"""
#         legend_elements = [
#             plt.Line2D([0], [0], color='blue', lw=3, label='预演数据流'),
#             plt.Line2D([0], [0], color='green', lw=3, label='控制指令流'),
#             plt.Line2D([0], [0], color='red', lw=3, label='实时控制流'),
#             plt.Line2D([0], [0], color='brown', lw=3, label='状态反馈流'),
#             plt.Line2D([0], [0], color='navy', lw=3, label='数据上传流'),
#             plt.Line2D([0], [0], color='purple', lw=3, label='调度指令流'),
#             plt.Line2D([0], [0], color='orange', lw=3, label='模式控制流')
#         ]
#
#         self.ax.legend(handles=legend_elements, loc='upper left',
#                        bbox_to_anchor=(0.02, 0.98), fontsize=10,
#                        title="数据流类型", title_fontsize=12,
#                        frameon=True, fancybox=True, shadow=True)
#
#     def export_diagram(self, filename="智能修井系统架构图.png"):
#         """直接导出架构图"""
#         self.create_architecture_diagram(save_path=filename)
#         print(f"架构图已导出为: {filename}")
#         return f"架构图已导出为: {filename}"
#
#     def get_architecture_description(self):
#         """获取架构描述"""
#         description = """
# 智能修井系统三层协同架构说明
# ==========================
#
# 架构设计原则
# -----------
# 1. **职责分离**: 每层有明确的职责边界
# 2. **实时性分级**: 不同业务有不同的实时性要求
# 3. **数据优化**: 减少不必要的数据传输
# 4. **安全隔离**: 关键控制与外部网络隔离
#
# 各层核心功能
# -----------
#
# ☁️ 云端层 - 智慧大脑
# ------------------
# - **定位**: 全局监控、规划与优化
# - **响应时间**: 秒级到分钟级
# - **主要组件**:
#   * 远程监控中心: 全局状态监控和人机交互
#   * 数字孪生体: 系统虚拟映射和仿真
#   * 修井预演模块: 操作流程预验证
#   * 大数据分析平台: 历史数据分析和优化
#   * 专家诊断系统: 远程故障诊断和支持
#
# 🖥️ 边缘层 - 智能中枢
# ------------------
# - **定位**: 本地实时决策与控制
# - **响应时间**: 毫秒级(1-50ms)
# - **主要组件**:
#   * 边缘服务器集群: 本地计算与协调
#   * 协同运动规划器: 多设备路径规划
#   * 机器视觉引擎: 实时图像识别与定位
#   * 实时控制逻辑: 闭环控制执行
#   * 数据网关: 协议转换与数据聚合
#   * 本地操作台: 应急与手动干预接口
#
# 🔧 现场层 - 执行手足
# ------------------
# - **定位**: 物理信号采集与设备驱动
# - **响应时间**: 微秒到毫秒级
# - **主要组件**:
#   * PLC/机器人控制器: 设备底层控制
#   * 伺服驱动器: 高精度运动执行
#   * 传感器网络: 压力、位移、温度等采集
#   * 执行器系统: 液压/电动执行机构
#   * 基地预装系统: 管柱/工具自动准备
# """
#         return description.strip()
#
#
# # draw_arch.py
# if __name__ == "__main__":
#     arch = IntelligentWorkoverSystemArchitecture()   # 实例化
#     arch.export_diagram()                            # 导出高清图
#     plt.show()
# #
# import matplotlib.pyplot as plt
# import matplotlib.patches as patches
# from matplotlib.patches import FancyBboxPatch, Rectangle, ConnectionPatch
# import numpy as np
# from io import BytesIO
# import base64
# from matplotlib.font_manager import FontProperties
# import platform
#
# class IntelligentWorkoverSystemArchitecture:
#     """智能修井系统三层协同架构"""
#
#     def __init__(self):
#         self.fig = None
#         self.ax = None
#         self.setup_architecture()
#
#     def setup_architecture(self):
#         """设置架构组件和数据流"""
#         self.layers = {
#             "cloud": {
#                 "name": "云端层 - 智慧大脑\n(全局监控、规划与优化)",
#                 "color": "#E3F2FD",
#                 "components": {
#                     "远程监控中心 HMI": {"pos": (0.5, 0.85), "color": "#FFEB3B"},
#                     "数字孪生体": {"pos": (0.25, 0.75), "color": "#4CAF50"},
#                     "修井预演模块": {"pos": (0.25, 0.65), "color": "#2196F3"},
#                     "大数据分析与AI平台": {"pos": (0.75, 0.75), "color": "#9C27B0"},
#                     "远程专家诊断系统": {"pos": (0.75, 0.65), "color": "#F44336"}
#                 }
#             },
#             "edge": {
#                 "name": "边缘层 - 智能中枢\n(本地实时决策与控制)",
#                 "color": "#F3E5F5",
#                 "components": {
#                     "边缘服务器集群": {"pos": (0.5, 0.45), "color": "#FF9800"},
#                     "协同运动规划器": {"pos": (0.15, 0.4), "color": "#3F51B5"},
#                     "机器视觉处理引擎": {"pos": (0.3, 0.4), "color": "#00BCD4"},
#                     "实时控制逻辑": {"pos": (0.7, 0.4), "color": "#8BC34A"},
#                     "数据网关(OPC UA/MQTT)": {"pos": (0.85, 0.4), "color": "#607D8B"},
#                     "本地操作台接口": {"pos": (0.5, 0.35), "color": "#E91E63"}
#                 }
#             },
#             "field": {
#                 "name": "现场层 - 执行手足\n(信号采集与驱动)",
#                 "color": "#E8F5E8",
#                 "components": {
#                     "PLC控制系统": {"pos": (0.2, 0.2), "color": "#3F51B5"},
#                     "机器人控制器": {"pos": (0.4, 0.2), "color": "#3F51B5"},
#                     "伺服驱动器系统": {"pos": (0.6, 0.2), "color": "#FF5722"},
#                     "传感器网络": {"pos": (0.8, 0.15), "color": "#673AB7"},
#                     "执行器系统": {"pos": (0.8, 0.1), "color": "#E53935"},
#                     "基地预装系统": {"pos": (0.2, 0.1), "color": "#795548"},
#                     "弹夹式管盒": {"pos": (0.1, 0.08), "color": "#A1887F"},
#                     "工具集装架": {"pos": (0.3, 0.08), "color": "#A1887F"}
#                 }
#             }
#         }
#
#         # 定义数据流
#         self.data_flows = [
#             # 云端内部流
#             ("数字孪生体", "修井预演模块", "预演生成", "blue"),
#             ("修井预演模块", "远程监控中心 HMI", "任务包提交", "blue"),
#
#             # 云端 -> 边缘
#             ("远程监控中心 HMI", "边缘服务器集群", "指令下发", "green"),
#             ("大数据分析与AI平台", "边缘服务器集群", "优化策略", "green"),
#             ("远程专家诊断系统", "边缘服务器集群", "诊断指令", "green"),
#
#             # 云端 -> 现场 (调度)
#             ("远程监控中心 HMI", "基地预装系统", "调度指令", "purple"),
#
#             # 边缘内部流
#             ("本地操作台接口", "边缘服务器集群", "模式切换", "orange"),
#
#             # 边缘 -> 现场 (控制)
#             ("边缘服务器集群", "PLC控制系统", "协同控制指令", "red"),
#             ("协同运动规划器", "机器人控制器", "运动轨迹", "red"),
#             ("机器视觉处理引擎", "机器人控制器", "视觉引导", "red"),
#             ("实时控制逻辑", "伺服驱动器系统", "驱动指令", "red"),
#
#             # 现场 -> 边缘 (反馈)
#             ("传感器网络", "数据网关(OPC UA/MQTT)", "实时数据", "brown"),
#             ("执行器系统", "数据网关(OPC UA/MQTT)", "状态反馈", "brown"),
#             ("PLC控制系统", "边缘服务器集群", "设备状态", "brown"),
#
#             # 边缘 -> 云端 (数据上传)
#             ("边缘服务器集群", "远程监控中心 HMI", "聚合数据", "navy"),
#             ("边缘服务器集群", "数字孪生体", "实时同步", "navy"),
#             ("边缘服务器集群", "大数据分析与AI平台", "分析数据", "navy"),
#             ("边缘服务器集群", "远程专家诊断系统", "诊断数据", "navy")
#         ]
#
#     def create_architecture_diagram(self, save_path=None):
#         """创建架构图"""
#         plt.close('all')  # 关闭之前的图
#
#         # === 🔧 修复中文字体问题 ===
#         # 根据操作系统选择合适的中文字体
#         system = platform.system()
#         if system == "Windows":
#             font_prop = FontProperties(family='SimHei', size=10)  # 黑体
#         elif system == "Darwin":  # macOS
#             font_prop = FontProperties(family='PingFang HK', size=10)  # 或 'STHeiti'
#         else:  # Linux
#             font_prop = FontProperties(family='WenQuanYi Micro Hei', size=10)  # 文泉驿
#
#         # 设置全局字体（备用方案）
#         plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei', 'WenQuanYi Micro Hei', 'Arial Unicode MS', 'sans-serif']
#         plt.rcParams['axes.unicode_minus'] = False  # 正常显示负号
#
#         self.fig, self.ax = plt.subplots(1, 1, figsize=(20, 15))
#         self.ax.set_xlim(0, 1)
#         self.ax.set_ylim(0, 1)
#         self.ax.set_aspect('equal')
#         self.ax.axis('off')
#
#         # 设置背景
#         self.ax.set_facecolor('#f8f9fa')
#
#         # 绘制标题
#         self.ax.text(0.5, 0.96, '智能修井机器人系统\n三层协同架构',
#                      ha='center', va='center', fontsize=20, fontweight='bold',
#                      bbox=dict(boxstyle="round,pad=0.5", facecolor='white', edgecolor='black'))
#
#         # 绘制各层
#         self._draw_layers()
#
#         # 绘制组件
#         self._draw_components()
#
#         # 绘制数据流
#         self._draw_data_flows()
#
#         # 添加图例
#         self._add_legend()
#
#         plt.tight_layout()
#
#         if save_path:
#             plt.savefig(save_path, dpi=300, bbox_inches='tight')
#             print(f"架构图已保存至: {save_path}")
#
#         return self.fig
#
#     def _draw_layers(self):
#         """绘制三层区域"""
#         layer_heights = {'cloud': 0.25, 'edge': 0.2, 'field': 0.2}
#         layer_y_positions = {'cloud': 0.7, 'edge': 0.45, 'field': 0.2}
#
#         for layer_id, layer_info in self.layers.items():
#             y_pos = layer_y_positions[layer_id]
#             height = layer_heights[layer_id]
#
#             # 绘制层背景
#             rect = FancyBboxPatch((0.02, y_pos - height / 2), 0.96, height,
#                                   boxstyle="round,pad=0.02", linewidth=2,
#                                   facecolor=layer_info['color'], edgecolor='black', alpha=0.8)
#             self.ax.add_patch(rect)
#
#             # 层标题
#             self.ax.text(0.5, y_pos + height / 2 - 0.05, layer_info['name'],
#                          ha='center', va='center', fontsize=14, fontweight='bold',
#                          bbox=dict(boxstyle="round,pad=0.3", facecolor='white', alpha=0.9))
#
#     def _draw_components(self):
#         """绘制所有组件"""
#         for layer_id, layer_info in self.layers.items():
#             for comp_name, comp_info in layer_info['components'].items():
#                 x, y = comp_info['pos']
#
#                 # 绘制组件框
#                 width, height = 0.16, 0.04
#                 if len(comp_name) > 8:  # 长名称调整宽度
#                     width = 0.2
#
#                 rect = FancyBboxPatch((x - width / 2, y - height / 2), width, height,
#                                       boxstyle="round,pad=0.01", linewidth=1.5,
#                                       facecolor=comp_info['color'], edgecolor='black', alpha=0.9)
#                 self.ax.add_patch(rect)
#
#                 # 组件名称
#                 fontsize = 8 if len(comp_name) <= 12 else 7
#                 self.ax.text(x, y, comp_name, ha='center', va='center',
#                              fontsize=fontsize, fontweight='bold',
#                              bbox=dict(boxstyle="round,pad=0.1", facecolor='white', alpha=0.8))
#
#     def _draw_data_flows(self):
#         """绘制数据流箭头"""
#         arrow_style = "->,head_width=0.05,head_length=0.1"
#
#         for source, target, label, color in self.data_flows:
#             source_pos = self._find_component_position(source)
#             target_pos = self._find_component_position(target)
#
#             if source_pos and target_pos:
#                 # 计算箭头路径
#                 dx = target_pos[0] - source_pos[0]
#                 dy = target_pos[1] - source_pos[1]
#
#                 # 绘制箭头
#                 self.ax.annotate("", xy=target_pos, xytext=source_pos,
#                                  arrowprops=dict(arrowstyle=arrow_style,
#                                                  color=color, alpha=0.7, lw=2))
#
#                 # 数据流标签
#                 mid_x = (source_pos[0] + target_pos[0]) / 2
#                 mid_y = (source_pos[1] + target_pos[1]) / 2
#
#                 # 根据方向调整标签位置避免重叠
#                 label_offset = 0.02
#                 if abs(dy) > abs(dx):  # 垂直流向
#                     label_x = mid_x + label_offset
#                 else:  # 水平流向
#                     label_y = mid_y + label_offset
#
#                 self.ax.text(mid_x, mid_y, label, fontsize=7, ha='center', va='center',
#                              bbox=dict(boxstyle="round,pad=0.2", facecolor='white',
#                                        edgecolor=color, alpha=0.8))
#
#     def _find_component_position(self, component_name):
#         """查找组件位置"""
#         for layer_info in self.layers.values():
#             for comp_name, comp_info in layer_info['components'].items():
#                 if comp_name == component_name:
#                     return comp_info['pos']
#         return None
#
#     def _add_legend(self):
#         """添加图例"""
#         legend_elements = [
#             plt.Line2D([0], [0], color='blue', lw=3, label='预演数据流'),
#             plt.Line2D([0], [0], color='green', lw=3, label='控制指令流'),
#             plt.Line2D([0], [0], color='red', lw=3, label='实时控制流'),
#             plt.Line2D([0], [0], color='brown', lw=3, label='状态反馈流'),
#             plt.Line2D([0], [0], color='navy', lw=3, label='数据上传流'),
#             plt.Line2D([0], [0], color='purple', lw=3, label='调度指令流'),
#             plt.Line2D([0], [0], color='orange', lw=3, label='模式控制流')
#         ]
#
#         self.ax.legend(handles=legend_elements, loc='upper left',
#                        bbox_to_anchor=(0.02, 0.98), fontsize=10,
#                        title="数据流类型", title_fontsize=12,
#                        frameon=True, fancybox=True, shadow=True)
#
#     def export_diagram(self, filename="智能修井系统架构图.png"):
#         """直接导出架构图"""
#         self.create_architecture_diagram(save_path=filename)
#         print(f"架构图已导出为: {filename}")
#         return f"架构图已导出为: {filename}"
#
#     def get_architecture_description(self):
#         """获取架构描述"""
#         description = """
# 智能修井系统三层协同架构说明
# ==========================
#
# 架构设计原则
# -----------
# 1. **职责分离**: 每层有明确的职责边界
# 2. **实时性分级**: 不同业务有不同的实时性要求
# 3. **数据优化**: 减少不必要的数据传输
# 4. **安全隔离**: 关键控制与外部网络隔离
#
# 各层核心功能
# -----------
#
# ☁️ 云端层 - 智慧大脑
# ------------------
# - **定位**: 全局监控、规划与优化
# - **响应时间**: 秒级到分钟级
# - **主要组件**:
#   * 远程监控中心: 全局状态监控和人机交互
#   * 数字孪生体: 系统虚拟映射和仿真
#   * 修井预演模块: 操作流程预验证
#   * 大数据分析平台: 历史数据分析和优化
#   * 专家诊断系统: 远程故障诊断和支持
#
# 🖥️ 边缘层 - 智能中枢
# ------------------
# - **定位**: 本地实时决策与控制
# - **响应时间**: 毫秒级(1-50ms)
# - **主要组件**:
#   * 边缘服务器集群: 本地计算与协调
#   * 协同运动规划器: 多设备路径规划
#   * 机器视觉引擎: 实时图像识别与定位
#   * 实时控制逻辑: 闭环控制执行
#   * 数据网关: 协议转换与数据聚合
#   * 本地操作台: 应急与手动干预接口
#
# 🔧 现场层 - 执行手足
# ------------------
# - **定位**: 物理信号采集与设备驱动
# - **响应时间**: 微秒到毫秒级
# - **主要组件**:
#   * PLC/机器人控制器: 设备底层控制
#   * 伺服驱动器: 高精度运动执行
#   * 传感器网络: 压力、位移、温度等采集
#   * 执行器系统: 液压/电动执行机构
#   * 基地预装系统: 管柱/工具自动准备
# """
#         return description.strip()
#
#
# # draw_arch.py
# if __name__ == "__main__":
#     arch = IntelligentWorkoverSystemArchitecture()   # 实例化
#     arch.export_diagram()                            # 导出高清图
#     plt.show()                                       # 弹出窗口预览（可选）


import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.patches import FancyBboxPatch, Rectangle, ConnectionPatch
import numpy as np
from io import BytesIO
import base64
from matplotlib.font_manager import FontProperties
import platform
import os


class IntelligentWorkoverSystemArchitecture:
    """智能修井系统三层协同架构"""

    def __init__(self):
        self.fig = None
        self.ax = None
        self.setup_architecture()

    def setup_architecture(self):
        """设置架构组件和数据流"""
        self.layers = {
            "cloud": {
                "name": "云端层 - 智慧大脑\n(全局监控、规划与优化)",
                "color": "#E3F2FD",
                "components": {
                    "远程监控中心 HMI": {"pos": (0.5, 0.85), "color": "#FFEB3B"},
                    "数字孪生体": {"pos": (0.25, 0.75), "color": "#4CAF50"},
                    "修井预演模块": {"pos": (0.25, 0.65), "color": "#2196F3"},
                    "大数据分析与AI平台": {"pos": (0.75, 0.75), "color": "#9C27B0"},
                    "远程专家诊断系统": {"pos": (0.75, 0.65), "color": "#F44336"}
                }
            },
            "edge": {
                "name": "边缘层 - 智能中枢\n(本地实时决策与控制)",
                "color": "#F3E5F5",
                "components": {
                    "边缘服务器集群": {"pos": (0.5, 0.45), "color": "#FF9800"},
                    "协同运动规划器": {"pos": (0.15, 0.4), "color": "#3F51B5"},
                    "机器视觉处理引擎": {"pos": (0.3, 0.4), "color": "#00BCD4"},
                    "实时控制逻辑": {"pos": (0.7, 0.4), "color": "#8BC34A"},
                    "数据网关(OPC UA/MQTT)": {"pos": (0.85, 0.4), "color": "#607D8B"},
                    "本地操作台接口": {"pos": (0.5, 0.35), "color": "#E91E63"}
                }
            },
            "field": {
                "name": "现场层 - 执行手足\n(信号采集与驱动)",
                "color": "#E8F5E8",
                "components": {
                    "PLC控制系统": {"pos": (0.2, 0.2), "color": "#3F51B5"},
                    "机器人控制器": {"pos": (0.4, 0.2), "color": "#3F51B5"},
                    "伺服驱动器系统": {"pos": (0.6, 0.2), "color": "#FF5722"},
                    "传感器网络": {"pos": (0.8, 0.15), "color": "#673AB7"},
                    "执行器系统": {"pos": (0.8, 0.1), "color": "#E53935"},
                    "基地预装系统": {"pos": (0.2, 0.1), "color": "#795548"},
                    "弹夹式管盒": {"pos": (0.1, 0.08), "color": "#A1887F"},
                    "工具集装架": {"pos": (0.3, 0.08), "color": "#A1887F"}
                }
            }
        }

        # 定义数据流
        self.data_flows = [
            # 云端内部流
            ("数字孪生体", "修井预演模块", "预演生成", "blue"),
            ("修井预演模块", "远程监控中心 HMI", "任务包提交", "blue"),

            # 云端 -> 边缘
            ("远程监控中心 HMI", "边缘服务器集群", "指令下发", "green"),
            ("大数据分析与AI平台", "边缘服务器集群", "优化策略", "green"),
            ("远程专家诊断系统", "边缘服务器集群", "诊断指令", "green"),

            # 云端 -> 现场 (调度)
            ("远程监控中心 HMI", "基地预装系统", "调度指令", "purple"),

            # 边缘内部流
            ("本地操作台接口", "边缘服务器集群", "模式切换", "orange"),

            # 边缘 -> 现场 (控制)
            ("边缘服务器集群", "PLC控制系统", "协同控制指令", "red"),
            ("协同运动规划器", "机器人控制器", "运动轨迹", "red"),
            ("机器视觉处理引擎", "机器人控制器", "视觉引导", "red"),
            ("实时控制逻辑", "伺服驱动器系统", "驱动指令", "red"),

            # 现场 -> 边缘 (反馈)
            ("传感器网络", "数据网关(OPC UA/MQTT)", "实时数据", "brown"),
            ("执行器系统", "数据网关(OPC UA/MQTT)", "状态反馈", "brown"),
            ("PLC控制系统", "边缘服务器集群", "设备状态", "brown"),

            # 边缘 -> 云端 (数据上传)
            ("边缘服务器集群", "远程监控中心 HMI", "聚合数据", "navy"),
            ("边缘服务器集群", "数字孪生体", "实时同步", "navy"),
            ("边缘服务器集群", "大数据分析与AI平台", "分析数据", "navy"),
            ("边缘服务器集群", "远程专家诊断系统", "诊断数据", "navy")
        ]

    def create_architecture_diagram(self, save_path=None, dpi=1080, figsize=(20, 15)):
        """创建架构图"""
        plt.close('all')  # 关闭之前的图

        # === 🔧 修复中文字体问题 ===
        # 根据操作系统选择合适的中文字体
        system = platform.system()
        if system == "Windows":
            font_prop = FontProperties(family='SimHei', size=10)  # 黑体
        elif system == "Darwin":  # macOS
            font_prop = FontProperties(family='PingFang HK', size=10)  # 或 'STHeiti'
        else:  # Linux
            font_prop = FontProperties(family='WenQuanYi Micro Hei', size=10)  # 文泉驿

        # 设置全局字体（备用方案）
        plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei', 'WenQuanYi Micro Hei', 'Arial Unicode MS',
                                           'sans-serif']
        plt.rcParams['axes.unicode_minus'] = False  # 正常显示负号

        self.fig, self.ax = plt.subplots(1, 1, figsize=figsize)
        self.ax.set_xlim(0, 1)
        self.ax.set_ylim(0, 1)
        self.ax.set_aspect('equal')
        self.ax.axis('off')

        # 设置背景
        self.ax.set_facecolor('#f8f9fa')

        # 绘制标题
        self.ax.text(0.5, 0.96, '智能修井机器人系统\n三层协同架构',
                     ha='center', va='center', fontsize=24, fontweight='bold',
                     bbox=dict(boxstyle="round,pad=0.5", facecolor='white', edgecolor='black'))

        # 绘制各层
        self._draw_layers()

        # 绘制组件
        self._draw_components()

        # 绘制数据流
        self._draw_data_flows()

        # 添加图例
        self._add_legend()

        plt.tight_layout()

        if save_path:
            plt.savefig(save_path, dpi=dpi, bbox_inches='tight', facecolor='white', edgecolor='none')
            print(f"架构图已保存至: {save_path} (分辨率: {dpi} DPI)")
            print(f"图片尺寸: {figsize[0]} x {figsize[1]} 英寸")
            print(f"实际像素: {int(figsize[0] * dpi)} x {int(figsize[1] * dpi)} 像素")

        return self.fig

    def _draw_layers(self):
        """绘制三层区域"""
        layer_heights = {'cloud': 0.25, 'edge': 0.2, 'field': 0.2}
        layer_y_positions = {'cloud': 0.7, 'edge': 0.45, 'field': 0.2}

        for layer_id, layer_info in self.layers.items():
            y_pos = layer_y_positions[layer_id]
            height = layer_heights[layer_id]

            # 绘制层背景
            rect = FancyBboxPatch((0.02, y_pos - height / 2), 0.96, height,
                                  boxstyle="round,pad=0.02", linewidth=2,
                                  facecolor=layer_info['color'], edgecolor='black', alpha=0.8)
            self.ax.add_patch(rect)

            # 层标题
            self.ax.text(0.5, y_pos + height / 2 - 0.05, layer_info['name'],
                         ha='center', va='center', fontsize=16, fontweight='bold',
                         bbox=dict(boxstyle="round,pad=0.3", facecolor='white', alpha=0.9))

    def _draw_components(self):
        """绘制所有组件"""
        for layer_id, layer_info in self.layers.items():
            for comp_name, comp_info in layer_info['components'].items():
                x, y = comp_info['pos']

                # 绘制组件框
                width, height = 0.16, 0.04
                if len(comp_name) > 8:  # 长名称调整宽度
                    width = 0.2

                rect = FancyBboxPatch((x - width / 2, y - height / 2), width, height,
                                      boxstyle="round,pad=0.01", linewidth=1.5,
                                      facecolor=comp_info['color'], edgecolor='black', alpha=0.9)
                self.ax.add_patch(rect)

                # 组件名称
                fontsize = 10 if len(comp_name) <= 12 else 9
                self.ax.text(x, y, comp_name, ha='center', va='center',
                             fontsize=fontsize, fontweight='bold',
                             bbox=dict(boxstyle="round,pad=0.1", facecolor='white', alpha=0.8))

    def _draw_data_flows(self):
        """绘制数据流箭头"""
        arrow_style = "->,head_width=0.03,head_length=0.05"

        for source, target, label, color in self.data_flows:
            source_pos = self._find_component_position(source)
            target_pos = self._find_component_position(target)

            if source_pos and target_pos:
                # 计算箭头路径
                dx = target_pos[0] - source_pos[0]
                dy = target_pos[1] - source_pos[1]

                # 绘制箭头
                self.ax.annotate("", xy=target_pos, xytext=source_pos,
                                 arrowprops=dict(arrowstyle=arrow_style,
                                                 color=color, alpha=0.7, lw=1.5))

                # 数据流标签
                mid_x = (source_pos[0] + target_pos[0]) / 2
                mid_y = (source_pos[1] + target_pos[1]) / 2

                # 根据方向调整标签位置避免重叠
                label_offset = 0.02
                if abs(dy) > abs(dx):  # 垂直流向
                    label_x = mid_x + label_offset
                else:  # 水平流向
                    label_y = mid_y + label_offset

                self.ax.text(mid_x, mid_y, label, fontsize=8, ha='center', va='center',
                             bbox=dict(boxstyle="round,pad=0.2", facecolor='white',
                                       edgecolor=color, alpha=0.8))

    def _find_component_position(self, component_name):
        """查找组件位置"""
        for layer_info in self.layers.values():
            for comp_name, comp_info in layer_info['components'].items():
                if comp_name == component_name:
                    return comp_info['pos']
        return None

    def _add_legend(self):
        """添加图例"""
        legend_elements = [
            plt.Line2D([0], [0], color='blue', lw=3, label='预演数据流'),
            plt.Line2D([0], [0], color='green', lw=3, label='控制指令流'),
            plt.Line2D([0], [0], color='red', lw=3, label='实时控制流'),
            plt.Line2D([0], [0], color='brown', lw=3, label='状态反馈流'),
            plt.Line2D([0], [0], color='navy', lw=3, label='数据上传流'),
            plt.Line2D([0], [0], color='purple', lw=3, label='调度指令流'),
            plt.Line2D([0], [0], color='orange', lw=3, label='模式控制流')
        ]

        self.ax.legend(handles=legend_elements, loc='upper left',
                       bbox_to_anchor=(0.02, 0.98), fontsize=12,
                       title="数据流类型", title_fontsize=14,
                       frameon=True, fancybox=True, shadow=True)

    def export_diagram(self, filename="智能修井系统架构图.png", dpi=600):
        """导出架构图，支持超高分辨率"""
        self.create_architecture_diagram(save_path=filename, dpi=dpi)
        print(f"\n✅ 架构图已导出为: {filename}")
        print(f"   分辨率: {dpi} DPI")
        print(f"   文件大小: {os.path.getsize(filename) / 1024 / 1024:.2f} MB")
        return f"架构图已导出为: {filename} (分辨率: {dpi} DPI)"

    def get_architecture_description(self):
        """获取架构描述"""
        description = """
智能修井系统三层协同架构说明
==========================

架构设计原则
-----------
1. **职责分离**: 每层有明确的职责边界
2. **实时性分级**: 不同业务有不同的实时性要求  
3. **数据优化**: 减少不必要的数据传输
4. **安全隔离**: 关键控制与外部网络隔离

各层核心功能
-----------

☁️ 云端层 - 智慧大脑
------------------
- **定位**: 全局监控、规划与优化
- **响应时间**: 秒级到分钟级
- **主要组件**:
  * 远程监控中心: 全局状态监控和人机交互
  * 数字孪生体: 系统虚拟映射和仿真
  * 修井预演模块: 操作流程预验证
  * 大数据分析平台: 历史数据分析和优化
  * 专家诊断系统: 远程故障诊断和支持

🖥️ 边缘层 - 智能中枢  
------------------
- **定位**: 本地实时决策与控制
- **响应时间**: 毫秒级(1-50ms)
- **主要组件**:
  * 边缘服务器集群: 本地计算与协调
  * 协同运动规划器: 多设备路径规划
  * 机器视觉引擎: 实时图像识别与定位
  * 实时控制逻辑: 闭环控制执行
  * 数据网关: 协议转换与数据聚合
  * 本地操作台: 应急与手动干预接口

🔧 现场层 - 执行手足
------------------
- **定位**: 物理信号采集与设备驱动
- **响应时间**: 微秒到毫秒级
- **主要组件**:
  * PLC/机器人控制器: 设备底层控制
  * 伺服驱动器: 高精度运动执行
  * 传感器网络: 压力、位移、温度等采集
  * 执行器系统: 液压/电动执行机构
  * 基地预装系统: 管柱/工具自动准备
"""
        return description.strip()


# 主程序入口
if __name__ == "__main__":
    print("开始生成高清智能修井系统架构图...")
    print("配置参数: 分辨率600 DPI, 尺寸20x15英寸")

    arch = IntelligentWorkoverSystemArchitecture()  # 实例化
    arch.export_diagram("智能修井系统架构图_超清版.png", dpi=1080)  # 导出超高清图
    plt.show()  # 弹出窗口预览

    print("\n💡 提示: 如需更高清版本，可调整export_diagram中的dpi参数为1200或更高")
    print("   例如: arch.export_diagram('超超清图.png', dpi=1200)")



